#coding:utf8

import logging, time, os

class Logger():
    
    def __init__(self, path, prefix, format="%Y%m%d"):
        self.path  = path
        self.prefix = prefix
        self.handler = None
        self.format = format
        self.initlogger()
        self.logfile = self._getlogfile()
        
    def initlogger(self):
        self.logger = logging.getLogger(self.prefix)
        if self.handler is not None:
            self.logger.removeHandler(self.handler)
            self.handler.close()
        self.logfile = self._getlogfile()
        self.handler = logging.FileHandler(self.logfile)
        formatter    = logging.Formatter('%(asctime)s\t%(message)s')
        self.handler.setFormatter(formatter)    
        self.logger.addHandler(self.handler)
        self.logger.setLevel(logging.NOTSET)
    
    def _getlogfile(self):
        logname = self.prefix
        if len(self.format) > 0:
            logname = "%s-%s" % (self.prefix, time.strftime(self.format))
        return os.path.join(self.path, logname)
    
    def splitlog(self):
        if self.handler.baseFilename != self._getlogfile() and len(self.format) > 0:
            self.initlogger()
    
    def write(self, info):
        self.splitlog()
        self.logger.log(logging.WARNING, info)
    
    def log(self, info):
        self.write(info)

    def __call__(self, info):
        self.log(info)
